#include<iostream>
#include<string>
#include<cmath>
#include<algorithm>
#include<queue>
#include<cstring>
#include<cstdio>
using namespace std;
typedef long long ll;

int a[20];
ll dp[20][2];

ll dfs(int pos,int pre,int state,bool limit)
{
    if(pos==-1)return 1;
    if(!limit&&dp[pos][state]!=-1)return dp[pos][state];
    int up=limit?a[pos]:9;
    ll tmp=0;
    for(int i=0;i<=up;i++)
    {
        if(pre==4&&i==9)continue;
        tmp+=dfs(pos-1,i,i==4,limit&&i==a[pos]);//之前限制过了，如果此时i==a[pos]（上限），再限制
    }
    if(!limit)dp[pos][state]=tmp;
    return tmp;
}


ll solve(ll x)
{
    int pos=0;
    while(x)
    {
        a[pos++]=x%10;
        x/=10;
    }
    return dfs(pos-1,-1,0,true);//一开始是有限制的
}

int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        memset(dp,-1,sizeof(dp));
        ll n;
        scanf("%lld",&n);
        printf("%lld\n",n-solve(n)+1);
    }
    return 0;
}